package com.visikard.ui.activity;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.visikard.application.Constant;
import com.visikard.application.UIMessage;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.GetDetailsRedeemGiftKardTask;
import com.visikard.asynctask.GetDetailsRedeemTask;
import com.visikard.item.ItemRedeemDetails;
import com.visikard.item.ItemTransactionHistory;
import com.visikard.ui.R;
import com.visikard.ui.adapter.TransactionDetailGiftKardAdapter;
import com.visikard.utility.BitmapUtils;
import com.visikard.utility.UILImageUtils;

public class TransactionDetailGiftKardActivity extends BaseLoginCompleteActivity implements OnClickListener {
	
	public static final String MSG_ITEM_REDEEM_KARD_TRANSACTION = "itemTransactionRedeemGiftKard";
	
	private View header;
	private ListView listView;
	private ImageView imgGiftKard, iconKard;
	
	private TextView txtCurrent, detailGiftKard, detailRedeemed, detailRedeemNumber,
			txtKardName, txtTime, txtKardRedeemed, txtAddress, txtPaymentMethod, txtRedemptionCode;

	ItemTransactionHistory itemGifkard;
	
	ArrayList<ItemRedeemDetails> listItemDetails = new ArrayList<ItemRedeemDetails>();
	
	TransactionDetailGiftKardAdapter adapter;
	DateFormat timeFormat;
	DateFormat formatter;
	
	private BaseTask mAsyncTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.transaction_detail_gift_kard_activity);
		
		listView = (ListView)findViewById(R.id.listview);
		
		LayoutInflater inflater = LayoutInflater.from(TransactionDetailGiftKardActivity.this);
		header = inflater.inflate(R.layout.redeem_transaction_header, listView, false);
		
		imgGiftKard = (ImageView)header.findViewById(R.id.redeem_transaction_gift_image);
		iconKard = (ImageView)header.findViewById(R.id.redeem_transaction_detail_icon);
		txtCurrent = (TextView)header.findViewById(R.id.redeem_transaction_current);
		detailGiftKard = (TextView)header.findViewById(R.id.transaction_details_gift_kard);
		detailRedeemed = (TextView)header.findViewById(R.id.transaction_details_redeemed);
		detailRedeemNumber = (TextView)header.findViewById(R.id.transaction_details_number_redeemed);
		txtKardName = (TextView)header.findViewById(R.id.transaction_details_kard_name);
		txtTime = (TextView)header.findViewById(R.id.transaction_details_time);
		txtKardRedeemed = (TextView)header.findViewById(R.id.transaction_details_kard_redeemed);
		txtAddress = (TextView)header.findViewById(R.id.transaction_details_redeem_address);
		txtPaymentMethod = (TextView)header.findViewById(R.id.transaction_details_payment_method);
		txtRedemptionCode = (TextView)header.findViewById(R.id.transaction_details_redeem_code);
		
		itemGifkard = getIntent().getParcelableExtra(MSG_ITEM_REDEEM_KARD_TRANSACTION);
		
		formatter = new SimpleDateFormat(Constant.TIME_FORMAT_STR, Locale.US);
		timeFormat = new SimpleDateFormat(Constant.DATETIME_FULL_FORMAT, Locale.US);
		
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		int mWidth = metrics.widthPixels / 4;

		RelativeLayout.LayoutParams lyGiftKard = (RelativeLayout.LayoutParams) imgGiftKard.getLayoutParams();
		lyGiftKard.width = metrics.widthPixels;
		lyGiftKard.height = metrics.widthPixels * 2 / 3;
		
		RelativeLayout.LayoutParams lyKard = (RelativeLayout.LayoutParams) iconKard.getLayoutParams();
		int kardHeight = mWidth * 2 / 3;
		lyKard.width = kardHeight * 2 / 3;
		lyKard.height = kardHeight;
		
//		Utils.overrideFonts(header);
		listView.addHeaderView(header);
		listView.setHeaderDividersEnabled(false);		
		
		if(itemGifkard != null){
			
			mAsyncTask = new GetDetailsRedeemGiftKardTask(mHandler);
			mAsyncTask.execute(itemGifkard.getMerchantId(), itemGifkard.getRedeemedTransactionId(), itemGifkard.getPurchaseTransactionId());
			
//			ImageLoader.getInstance(TransactionDetailGiftKardActivity.this).loadImageCorner(imgGiftKard, itemGifkard.getImageGiftKard(),
//					Device.getDeviceWidth(), BitmapUtils.ROUND_ALL, 4, 3, R.drawable.kard_shadow_default_horizontal, 0,  0);
			UILImageUtils.loadImage(imgGiftKard, //image view
					itemGifkard.getImageGiftKard(), //url
					1, //size of view
					BitmapUtils.ROUND_ALL, //round all 
					4, // round size
					3, //shadow
					R.drawable.kard_shadow_default_horizontal, //shadow resource 
					0, 0);
			
//			ImageLoader.getInstance(TransactionDetailGiftKardActivity.this).loadImageCorner(iconKard, itemGifkard.getKardImage(),
//					Device.getDeviceWidth() / 5, BitmapUtils.ROUND_ALL, 4, 3, R.drawable.kard_shadow_default_horizontal, 0,  0);
			UILImageUtils.loadImage(iconKard, itemGifkard.getKardImage(), 1, BitmapUtils.ROUND_ALL, 4, 3, R.drawable.kard_shadow_default_horizontal, 0, 0);
			
			txtCurrent.setText(getResources().getString(R.string.transactions_current_value) + " $" + String.format("%.2f", Double.parseDouble(itemGifkard.getRemainingValue())));
			try {
				if(itemGifkard.getIscoupon() == 0){
					detailRedeemed.setText(getResources().getString(R.string.transactions_redeem_detail_redeemed) + "\n $" + String.format("%.2f", Double.parseDouble(itemGifkard.getRedemptionValue())));
				}else{
					detailRedeemed.setText(getResources().getString(R.string.transactions_redeem_detail_redeemed) + "\n " + itemGifkard.getRedemptionValue());
				}
				if(itemGifkard.getIscoupon() == 0 && itemGifkard.getIsGiftSpecial() == 0)
					detailGiftKard.setText(getResources().getString(R.string.transactions_redeem_detail_gift_kard) + "\n $" + String.format("%.2f", Double.parseDouble(itemGifkard.getOriginalAmount())));
				else
					detailGiftKard.setText(getResources().getString(R.string.transactions_redeem_detail_gift_kard) + "\n " + itemGifkard.getOriginalAmount());
				
//				txtKardRedeemed.setText(getResources().getString(R.string.transactions_redeem_detail_redeemed) + ": $" + String.format("%.2f", Double.parseDouble(itemGifkard.getRemainingValue())));
				txtKardRedeemed.setText(getResources().getString(R.string.transactions_redeem_detail_redeemed) + ": $" + String.format("%.2f", Double.parseDouble(itemGifkard.getRedemptionValue())));
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			txtKardName.setText(itemGifkard.getKardName());
			try {
				txtTime.setText(getResources().getString(R.string.transactions_date) + " " + timeFormat.format(formatter.parse(itemGifkard.getDateTimeWithTimezone())));
			} catch (NotFoundException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			loadData();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			overridePendingTransition(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_to_right);
			break;

		default:
			break;
		}
	}
	
	private void loadData(){
		detailRedeemNumber.setText(getResources().getString(R.string.transactions_redeem_detail_number_redeemed) + "\n " + itemGifkard.getRedeemedCount());
		txtAddress.setText(itemGifkard.getAddress());
		
		if(!itemGifkard.getPaymentMethod().isEmpty())
			txtPaymentMethod.setText(itemGifkard.getPaymentMethod());
		else
			txtPaymentMethod.setText(getString(R.string.txt_redeem));
		
		txtRedemptionCode.setText(itemGifkard.getRedeemptionCode());
		
		if (adapter == null) {
			adapter = new TransactionDetailGiftKardAdapter(
					TransactionDetailGiftKardActivity.this, listItemDetails, itemGifkard.getKardName(), itemGifkard.getIscoupon(), itemGifkard.getKardImage());
			listView.setAdapter(adapter);
		} else
			adapter.notifyDataSetChanged();
	}	
	
	//Handle message method
	@Override
	protected boolean handleMessage(Message msg){
		switch (msg.what) {
		case UIMessage.MSG_LOAD_DETAIL_HISTORY_SUCCESS:
			//fill data from msg
			Bundle data = msg.getData();
			if(data != null){
				itemGifkard.setRedeemedCount(data.getInt(GetDetailsRedeemTask.KEY_REDEEM_COUNT));
				itemGifkard.setKardNumber(data.getString(GetDetailsRedeemTask.KEY_KARD_NUMBER));
				itemGifkard.setAddress(data.getString(GetDetailsRedeemTask.KEY_ADDRESS));
				itemGifkard.setStatus(data.getString(GetDetailsRedeemTask.KEY_STATUS));
				listItemDetails = data.getParcelableArrayList(GetDetailsRedeemTask.KEY_OTHER_REDEEM);
				itemGifkard.setPaymentMethod(data.getString(GetDetailsRedeemTask.KEY_PAYMENT_METHOD));
				itemGifkard.setRedeemptionCode(data.getString(GetDetailsRedeemTask.KEY_REDEEM_CODE));
				loadData();	
			}			
			return true;
		}
		return super.handleMessage(msg);
	}	

}
